﻿/*
 * 由SharpDevelop创建。
 * 用户： PC
 * 日期: 2018/01/14
 * 时间: 13:36
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing.Printing;
namespace printerhook
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	class mycls
	{
		private string m_str;
		private string m_strtype;
		private SerialPort sp;
		public string str
		{
			get {return m_str;}
			set {m_str=value;}
		}
		public string strtype
		{
			get {return m_strtype;}
			set {m_str=value;}
		}
		public SerialPort port
		{
			get{return sp;}
			set{sp=value;}
		}
		public mycls(string str,string strtype,SerialPort port)
		{
			m_str=str;
			m_strtype=strtype;
			sp=port;
		}
		
	}
	public partial class MainForm : Form
	{
		
		public bool sendRts=false;
		public System.Threading.Thread sendDataThread;
		private SerialPort S1=new SerialPort();
		private SerialPort S2=new SerialPort();
		PrintDocument printer=new PrintDocument();
		public MainForm()
		{
			
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			this.S1.DataReceived+=new SerialDataReceivedEventHandler(this.DateRecv);
			Control.CheckForIllegalCrossThreadCalls = false; 
			printer.PrintPage+=new PrintPageEventHandler(this.print_doc);
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		void print_doc(object sender,PrintPageEventArgs e)
		{
			try{
			int y=0;
			int jg=15;
			int lineend=180;
			Graphics g = e.Graphics;
			SolidBrush myBrush = new SolidBrush(Color.Black);//刷子
			string str = this.t_recv.Text;
			Font printFont=new Font("宋体",12,FontStyle.Bold);
			g.DrawString("古茗茶饮PRATO店",printFont,myBrush,30,y);
			
			printFont=new Font("宋体",10);
			y=y+jg+5;
			g.DrawString("店名  001",printFont,myBrush,100,y);
			y=y+jg;
			string tmp =Regex.Match(str,"\\d{8}").ToString();
			if(tmp==""){return;}
			g.DrawString("单号  "+tmp.Substring(5),printFont,myBrush,10,y);
			g.DrawString("机器  103",printFont,myBrush,100,y);
			Pen p=new Pen(Color.Black,1.0F);
			p.DashPattern= new float[]{2,2};
			g.DrawLine(p,0,y+jg,lineend,y+jg);
			y=y+jg+5;
			int old=0;
			old=y;
			//g.DrawString("项目  数量  单价 小计",printFont,myBrush,10,y);
			g.DrawLine(p,0,y+jg,lineend,y+jg);
			y=y+jg+5;
			int count=0;
			decimal money=0;
			string xiaoji="";
			string danjia="";
			MatchCollection mc =Regex.Matches(str,"\\d+\\.\\d+\\.\\d\\d.+\\n");
			
			foreach(Match m in mc)
			{
				tmp=m.ToString();
				xiaoji = tmp.Substring(0,tmp.IndexOf(".")+3);
				danjia = tmp.Substring(tmp.IndexOf(".")+3,tmp.LastIndexOf(".")+3-xiaoji.Length);

				int unit=Convert.ToInt32(Regex.Match(tmp.Replace(xiaoji+danjia,""),"\\d+").ToString());
				count+=unit;
				money+=Convert.ToDecimal(xiaoji);
				tmp=tmp.Replace(xiaoji+danjia+unit.ToString(),"");
				g.DrawString(tmp ,printFont,myBrush,10,y);
				y+=jg;
				g.DrawString(unit.ToString(),printFont,myBrush,60,y);
				g.DrawString(danjia.Substring(0,danjia.IndexOf(".")+2),printFont,myBrush,100,y);
				g.DrawString(xiaoji.Substring(0,xiaoji.IndexOf(".")+2),printFont,myBrush,140,y);
				y=y+jg;
			}
			g.DrawString(count.ToString()+"项目",printFont,myBrush,10,old);//项目  数量      小计
			g.DrawLine(p,0,y+5,lineend,y+5);
			y=y+10;
			g.DrawString("总计    "+decimal.Round(money,1),printFont,myBrush,10,y);
			g.DrawLine(p,0,y+jg+5,lineend,y+jg+5);
			g.DrawLine(p,0,y+55,1,y+55);
			}
			catch{}
		}
		void MainFormUnload(object sender,FormClosingEventArgs e)
		{
			if (S1.IsOpen) 
			{S1.Close();}
		}
		void MainFormLoad(object sender, EventArgs e)
		{
			string[] str = SerialPort.GetPortNames();
			if (str==null){
				MessageBox.Show ("本机没有串口","Error");
				return;
			}
			
			foreach (string s in SerialPort.GetPortNames())
			{
				cbSerial.Items.Add (s);
			}
			foreach(string s in PrinterSettings.InstalledPrinters)
			{
				cbSerialOut.Items.Add(s);
				
			}
			cbSerial.SelectedIndex=0;
			
			cbSerialOut.SelectedIndex=0;
			if( S1.IsOpen){S1.Close();}
			SetSerialPort(S1,"COM6" );
			OpenSerialPoart(S1);
			printer.PrinterSettings.PrinterName="POS58"; //"POS58";Microsoft XPS Document Writer
			
		}
		
		void BtnopenClick(object sender, EventArgs e)
		{
			if (btnopen.Text=="关闭" | S1.IsOpen)
			{
				S1.Close();
				btnopen.Text="打开";
				cbSerial.Enabled=true;
			}
			else{
				SetSerialPort(S1,cbSerial.Text );
				OpenSerialPoart(S1);
				btnopen.Text="关闭";
				cbSerial.Enabled=false;
			}
		}
		private void SetSerialPort(SerialPort sp,string PortName)
		{
			sp.PortName=PortName;
			sp.BaudRate =9600;
			sp.DataBits=8;
			sp.StopBits=StopBits.One;
			sp.Parity=Parity.None;
		}
		
		
		private void OpenSerialPoart(SerialPort sp)
		{
			try
			{
				sp.Open();
				
			}
			catch
			{
				MessageBox.Show(sp.PortName +"不能被打开","Error");
				sp.Close();
			}
		}



		private void DateRecv(object sender,SerialDataReceivedEventArgs e)
		{
			try{
			//string recvStr=S1.ReadExisting();
			byte[] recvBytes=new byte[S1.BytesToRead];
			S1.Read(recvBytes,0,recvBytes.Length);
			S1.DiscardInBuffer();
			string str="";
			for (int i =0;i<recvBytes.Length;i++)
			{
				str+=recvBytes[i].ToString("X2")+ " ";
			}
			str=Regex.Replace(str,"1B 63 .?.? .?.? ","");
			str=Regex.Replace(str,"1B 4A .?.? ","");
			str=Regex.Replace(str,"1B 33 .?.? ","");
			str=Regex.Replace(str,"1B 21 .?.? ","");
			str=Regex.Replace(str,"1B 25 .?.? ","");
			str=Regex.Replace(str,"1D 2F .?.? ","");
			
			str=str.Replace("1B 32 ","");
			str=str.Replace("1B 0E ","");
			str=str.Replace("1B 14 ","");
			str=str.Replace("1B 40 ","");
			str=str.Replace("1D 62 01 ","");
			str=str.Replace(" 00","");
			if (hextostring(t_recvhex.Text+ str).IndexOf("服务员")>0){
				
				str= t_recvhex.Text+ str;
				//int od=str.LastIndexOf("0A ");
				//t_recv.Text=hextostring(str.Substring(1,od));
				t_recv.Text=hextostring(str);
				t_recvhex.Text="";
				printer.Print();
			}else{
				t_recvhex.Text= t_recvhex.Text+ str;
			}
			}
			catch{}
			
		}
		private string hextostring(string hexstring)
		{
			try{
			string res=null;
			string[] tmp=hexstring.Split(' ');
			byte[] byts=new byte[tmp.Length];
			int i=0;
			foreach(string hex in tmp)
			{
				if (hex!=""){
					int val=Convert.ToInt32(hex,16);
					res+=(char)val;
					byts[i]=(byte)val;
					i++;
				}
			}
			return Encoding.Default.GetString(byts);
			}
			catch{
				return "";
			}
		}
		
		void BtnOutClick(object sender, EventArgs e)
		{
			try{
			printer.Print();
			}
			catch
			{
				
			}
		}
	}

}
